<?php

/**
 *    资金管理控制器
 *
 */
class account_checkApp extends BackendApp {

    //查看资金流水
    function index() {
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style' => 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $account_check_mod = &m('account_check');
        $conditions = $this->_get_query_conditions(array(array(
                'field' => 'user_name', //按用户名,店铺名,支付方式名称进行搜索
                'equal' => 'LIKE',
                'name' => 'user_name',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_from',
                'equal' => '>=',
                'handler' => 'gmstr2time',
            ), array(
                'field' => 'add_time',
                'name' => 'add_time_to',
                'equal' => '<=',
                'handler' => 'gmstr2time_end',
            ),
        ));
        if (in_array($_GET['wrong'], array('0', '1', '2'))) {
            $conditions .= ' AND wrong=' . $_GET['wrong'];
        }
        $page = $this->_get_page(10);
        $account_check_list = $account_check_mod->find(array(
            'conditions' => '1=1' . $conditions,
            'limit' => $page['limit'],
            'order' => "add_time desc,wrong desc",
            'count' => true));
        foreach ($account_check_list as $key => $val) {
            $my_account_check = $account_check_mod->get(array(
                'conditions' => 'user_id=' . $val['user_id'] . ' AND id<' . $val['id'],
                'order' => 'id desc'
            ));
            $account_check_list[$key]['begin_id'] = $my_account_check['last_id'];
            $account_check_list[$key]['begin_money'] = $my_account_check['money'];
            $account_check_list[$key]['begin_money_dj'] = $my_account_check['money_dj'];
        }
        $page['item_count'] = $account_check_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        $this->assign('filtered', $conditions ? 1 : 0); //是否有查询条件
        $this->assign('account_check_list', $account_check_list);
        $this->display('account_check.index.html');
    }

    function gen() {
        $account_log_mod = & m('account_log');
        $member_mod = & m('member');
        $order_mod = & m('order');
        $account_check_mod = & m('account_check');
		$member_mod->db->query('start transaction');
        $gen_user_id = $account_check_mod->getCol('SELECT user_id FROM ' . $account_check_mod->table . ' WHERE add_time>' . strtotime(date('Y-m-d')).' FOR UPDATE');
		$account_log_mod->getCol('SELECT id FROM ' . $account_log_mod->table . ' WHERE user_id>0 AND if_calcu=0 FOR UPDATE');
        $o_user_ids = $user_ids = $account_log_mod->getCol('SELECT user_id FROM ' . $account_log_mod->table . ' WHERE user_id>0 AND if_calcu=0 GROUP BY user_id');
        if (!$user_ids) {
			$member_mod->db->query('rollback');
            $this->show_warning('没有预存款记录');
            return;
        }
        if (is_array($user_ids) && is_array($gen_user_id)) {
            $user_ids = array_diff($user_ids, $gen_user_id);
        }
        if (is_array($user_ids) && is_array($_SESSION['wrong_user_id'])) {
            $user_ids = array_diff($user_ids, $_SESSION['wrong_user_id']);
        }
        if (!$user_ids) {
			$member_mod->db->query('rollback');
            //print_r($_SESSION['wrong_user_id']);
            $this->show_warning('没有新的预存款记录');
            return;
        }
        $user_ids = array_values($user_ids);
        $j = 0;
        if (!isset($_SESSION['gen_index'])) {
            $_SESSION['gen_index'] = 0;
        }
        for ($i = 0; $i < count($user_ids); $i++) {
            if ($j == 500) {
                break;
            }
            $j++;
            $order_ids = array();
            $member_info = $member_mod->get(array(
                'conditions' => 'user_id=' . $user_ids[$i],
                'fields' => 'money,money_dj'
            ));
            $money = floatval($member_info['money']);
            $money_dj = floatval($member_info['money_dj']);


            $account_check = $account_check_mod->get(array(
                'conditions' => 'user_id=' . $user_ids[$i],
                'fields' => 'last_id,money,money_dj',
                'order' => 'id desc'
            ));
            if ($account_check['wrong'] == '1') {
                $_SESSION['wrong_user_id'][] = $user_ids[$i];
                continue;
            }
            $order_ids = $account_log_mod->getCol('SELECT distinct(order_id) FROM ' . $account_log_mod->table . ' WHERE user_id=' . $user_ids[$i].' AND if_calcu=0');
            $income_1 = floatval($account_log_mod->getOne('SELECT SUM(money) FROM ' . $account_log_mod->table . ' WHERE user_id=' . $user_ids[$i] . ' AND complete=1 AND money_flow="income" AND if_calcu=0'));
            $outlay_1 = floatval($account_log_mod->getOne('SELECT SUM(money) FROM ' . $account_log_mod->table . ' WHERE user_id=' . $user_ids[$i] . ' AND complete=1 AND money_flow="outlay" AND if_calcu=0'));
            $income_2=0;//$income_2 = floatval($order_mod->getOne('SELECT SUM(order_amount) FROM ' . $order_mod->table . ' WHERE seller_id=' . $user_ids[$i] . ' AND payment_code NOT ' . 'IN("","code","bank","post")' . ' AND status=' . ORDER_FINISHED . ($order_ids ? (' AND order_id' . db_create_in($order_ids)) : ' AND order_id=0')));
            $outlay_2=0;//$outlay_2 = floatval($order_mod->getOne('SELECT SUM(order_amount) FROM ' . $order_mod->table . ' WHERE buyer_id=' . $user_ids[$i] . ' AND payment_code NOT ' . 'IN("","code","bank","post")' . ' AND status=' . ORDER_FINISHED . ($order_ids ? (' AND order_id' . db_create_in($order_ids)) : ' AND order_id=0')));
            $outlay_temp = floatval($order_mod->getOne('SELECT SUM(order_amount) FROM ' . $order_mod->table . ' WHERE buyer_id=' . $user_ids[$i] . ' AND payment_code NOT ' . 'IN("","code","bank","post")' . ' AND status' . db_create_in(array(ORDER_ACCEPTED, ORDER_SHIPPED)) . ($order_ids ? (' AND order_id' . db_create_in($order_ids)) : ' AND order_id=0')));
            //$outlay_temp=bcadd($outlay_temp,floatval($account_log_mod->getOne('SELECT SUM(money) FROM '.$account_log_mod->table.' WHERE user_id='.$user_ids[$i].' AND complete=0 AND money_flow="outlay" AND type ='.ACCOUNT_TYPE_TX.($account_check?(' AND id>'.$account_check['last_id']):''))),2);
            $income_temp = floatval($order_mod->getOne('SELECT SUM(order_amount) FROM ' . $order_mod->table . ' WHERE seller_id=' . $user_ids[$i] . ' AND payment_code NOT ' . 'IN("","code","bank","post")' . ' AND status' . db_create_in(array(ORDER_ACCEPTED, ORDER_SHIPPED)) . ($order_ids ? (' AND order_id' . db_create_in($order_ids)) : ' AND order_id=0')));
            $last_id = intval($account_log_mod->getOne('SELECT id FROM ' . $account_log_mod->table . ' WHERE user_id=' . $user_ids[$i].' AND if_calcu=0' . ' ORDER BY id desc'));
            !$last_id && $last_id = intval($account_check['last_id']);
            $wrong = (bcadd(bcadd(bcadd(bcadd($income_1, $income_2, 2), $income_temp, 2), floatval($account_check['money']), 2), floatval($account_check['money_dj']), 2) == bcadd(bcadd(bcadd(bcadd($outlay_1, $outlay_2, 2), $money, 2), $money_dj, 2), $outlay_temp, 2)) ? 0 : 1;
            if (!$income_1 && !$outlay_1 && !$income_2 && !$outlay_2 && !$outlay_temp && !$income_temp && !$wrong) {
                $_SESSION['wrong_user_id'][] = $user_ids[$i];
                continue;
            }
            $account_check_id=$account_check_mod->add(array(
                'user_id' => $user_ids[$i],
                'user_name' => $member_mod->getOne('SELECT user_name FROM ' . $member_mod->table . ' WHERE user_id=' . $user_ids[$i]),
                'money' => $money,
                'money_dj' => $money_dj,
                'income_temp' => $income_temp,
                'income' => bcadd($income_1, $income_2, 2),
                'outlay' => bcadd($outlay_1, $outlay_2, 2),
                'add_time' => gmtime(),
                'last_id' => $last_id,
                'wrong' => $wrong,
                'outlay_temp' => $outlay_temp,
            ));
            $account_log_mod->edit('user_id=' . $user_ids[$i] . ' AND id<=' . $last_id . ' AND if_calcu=0', 'if_calcu='.$account_check_id);
        }
		$member_mod->db->query('commit');
        //echo $_SESSION['gen_index'].'@'.count($account_check_mod->getCol('SELECT user_id FROM '.$account_check_mod->table.' WHERE add_time>'.strtotime(date('Y-m-d'))));
        if ($_SESSION['gen_index'] < count($o_user_ids)) {
            $_SESSION['gen_index'] += 500;
            $lnk = 'index.php?app=account_check&act=gen';
            $this->assign('title', '已完成' . $_SESSION['gen_index'] . '/' . count($o_user_ids) . '，3秒后程序将自动继续运行');
            $this->assign('auto_redirect', 1);
            $this->assign('auto_link', $lnk);
            $this->display('account_check.message.html');
        } else {
            $_SESSION['gen_index'] = 0;
            $_SESSION['wrong_user_id'] = array();
            $this->show_message('预存款对账生成成功', 'back_list', 'index.php?app=account_check');
            return;
        }
    }

    function edit() {
        $id = intval($_GET['id']);
        $account_check_mod = &m('account_check');
        $account_check = $account_check_mod->get($id);
        if (!$account_check || !$account_check['wrong']) {
            $this->show_warning('没有该账单');
        }
        //$account_check['begin_money']=$account_check_mod->getOne('SELECT money FROM '.$account_check_mod->table.' WHERE user_id='.$account_check['user_id'].' AND id<'.$account_check['id'].' ORDER BY id desc');
        $my_account_check = $account_check_mod->get(array(
            'conditions' => 'user_id=' . $account_check['user_id'] . ' AND id<' . $account_check['id'],
            'order' => 'id desc'
        ));
        $account_check['begin_money'] = $my_account_check['money'];
        $account_check['begin_money_dj'] = $my_account_check['money'];

        if (!IS_POST) {
            $this->assign('account_check', $account_check);
            $this->display('account_check.form.html');
        } else {
            $member_mod = & m('member');
            $member_mod->db->query('start transaction');
            $type = $_POST['type'];
            if (!in_array($type, array('money', 'money_dj'))) {
                $member_mod->db->query('rollback');
                $this->show_warning('Hacking Attempt');
                return;
            }
            $jia_or_jian = $_POST['jia_or_jian'];
            if (!in_array($jia_or_jian, array('jia', 'jian'))) {
                $member_mod->db->query('rollback');
                $this->show_warning('Hacking Attempt');
                return;
            }
            $post_money = floatval($_POST['post_money']);
            if ($post_money < 0) {
                $member_mod->db->query('rollback');
                $this->show_warning('调整金额不能为负数');
                return;
            }

            if ($post_money > 0) {
                if ($jia_or_jian == 'jian') {
                    $member = $member_mod->get(array(
                        'conditions' => 'user_id=' . $account_check['user_id'],
                        'fields' => 'money,money_dj'
                    ));
                    if (!$member) {
                        $member_mod->db->query('rollback');
                        $this->show_warning('用户不存在');
                        return;
                    }
                    if ($type == 'money') {
                        if ($member['money'] < $post_money) {
                            $member_mod->db->query('rollback');
                            $this->show_warning('用户可用余额不足');
                            return;
                        } else {
                            $mysql_flag = $account_check_mod->edit($id, 'money=money-' . $post_money);
                            if (!$mysql_flag) {
                                $member_mod->db->query('rollback');
                                $this->show_warning($account_check_mod->get_error());
                                return;
                            }
                            $mysql_flag = $member_mod->edit($account_check['user_id'], 'money=money-' . $post_money);
                            if (!$mysql_flag) {
                                $member_mod->db->query('rollback');
                                $this->show_warning($member_mod->get_error());
                                return;
                            }
                        }
                    }
                    if ($type == 'money_dj') {
                        if ($member['money_dj'] < $post_money) {
                            $member_mod->db->query('rollback');
                            $this->show_warning('用户冻结余额不足');
                            return;
                        } else {
                            $mysql_flag = $account_check_mod->edit($id, 'money_dj=money_dj-' . $post_money);
                            if (!$mysql_flag) {
                                $member_mod->db->query('rollback');
                                $this->show_warning($account_check_mod->get_error());
                                return;
                            }
                            $mysql_flag = $member_mod->edit($account_check['user_id'], 'money_dj=money_dj-' . $post_money);
                            if (!$mysql_flag) {
                                $member_mod->db->query('rollback');
                                $this->show_warning($member_mod->get_error());
                                return;
                            }
                        }
                    }
                } else {
                    if ($type == 'money') {
                        $mysql_flag = $account_check_mod->edit($id, 'money=money+' . $post_money);
                        if (!$mysql_flag) {
                            $member_mod->db->query('rollback');
                            $this->show_warning($account_check_mod->get_error());
                            return;
                        }
                        $mysql_flag = $member_mod->edit($account_check['user_id'], 'money=money+' . $post_money);
                        if (!$mysql_flag) {
                            $member_mod->db->query('rollback');
                            $this->show_warning($member_mod->get_error());
                            return;
                        }
                    }
                    if ($type == 'money_dj') {
                        $mysql_flag = $account_check_mod->edit($id, 'money_dj=money_dj+' . $post_money);
                        if (!$mysql_flag) {
                            $member_mod->db->query('rollback');
                            $this->show_warning($account_check_mod->get_error());
                            return;
                        }
                        $mysql_flag = $member_mod->edit($account_check['user_id'], 'money_dj=money_dj+' . $post_money);
                        if (!$mysql_flag) {
                            $member_mod->db->query('rollback');
                            $this->show_warning($member_mod->get_error());
                            return;
                        }
                    }
                }
            }

            $account_fix_mod = & m('account_fix');
            $account_fix_mod->add(array(
                'user_id' => $account_check['user_id'],
                'user_name' => $account_check['user_name'],
                'admin_id' => $this->visitor->info['user_id'],
                'admin_name' => $this->visitor->info['user_name'],
                'add_time' => gmtime(),
                'log_text' => $_POST['log_text'],
                'money' => $post_money,
                'type' => $type,
                'money_flow' => ($jia_or_jian == 'jian') ? 'outlay' : 'income',
                'complete' => ($_POST['wrong'] == '2') ? 1 : 0,
                'check_id' => $id
            ));
            if ($_POST['wrong'] == '2') {
                $mysql_flag = $account_check_mod->edit($id, 'wrong=2');
                if (!$mysql_flag) {
                    $member_mod->db->query('rollback');
                    $this->show_warning($account_check_mod->get_error());
                    return;
                }
            }
            $member_mod->db->query('commit');
            $this->show_message('修正成功', 'back_list', 'index.php?app=account_check');
            return;
        }
    }

    function fix() {
        $id = intval($_GET['id']);
        $account_fix_mod = & m('account_fix');
        $page = $this->_get_page(10);
        $account_fix_list = $account_fix_mod->find(array(
            'conditions' => 'check_id=' . $id,
            'limit' => $page['limit'],
            'count' => true
        ));
        $page['item_count'] = $account_fix_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign('account_check_list', $account_fix_list);
        $this->display('account_check.fix.html');
    }

}
